<template>
  <div class="login-wrapper" :style="'background-image:url('+ Background +')'">
    <div class="form-box">
      <div class="form-title">
        <img src="../assets/img/logo2.png" alt="icon">
        <p>登 录</p>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="0px" class="login-form">
        <el-form-item prop="username">
          <el-input ref="username" v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入手机号码"
                    maxlength="11" 　prefix-icon="el-icon-user"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-row :gutter="15">
            <el-col :span="50">
              <el-input v-model="loginForm.password" auto-complete="off" placeholder="请输入验证码"
                        maxlength="6" prefix-icon="el-icon-lock" @keyup.enter.native="handleLogin">
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" 　:disabled="!show" ref="smssend" @click="sendSMS()">{{ count?count:'发送验证码'}}</el-button>
            </el-col>
          </el-row>

        </el-form-item>
        <!--        <el-form-item>
                  <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
                </el-form-item>-->
        <el-form-item>
          <el-button :loading="loading" size="small" type="primary" style="width:100%;"
                     @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Background from '../assets/img/login-background.jpg'

export default {
  name: 'Login',
  data() {
    var checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else {
        let reg = /^1[0-9]{10}$/;
        if(!reg.test(value)){
          callback(new Error('手机号码不正确'));
        }
        callback();
      }
    };

    return {
      Background,
      loginForm: {
        username: '',
        password: '',
        rememberMe: true
      },
      loginRules: {
        username: [
          {required: true, trigger: 'blur', message: '手机号码不能为空'},
          {validator:checkPhone,trigger: 'blur',message: '手机号码不正确'}

          ],
        password: [{required: true, trigger: 'blur', message: '验证码不能为空'}]
      },
      loading: false,
      redirect: undefined,
      show: false,
      count: '发送验证码',
      timer: null,
      firstLoading: true
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.username.focus()
      this.triggerSMSCode();
    })
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const data = {
          mobile: this.loginForm.username,
          code: this.loginForm.password,
          clientId: 'myWeb'
        }
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('Login', data)
            .then(res => {
              window.location.reload();
             // this.$router.push('/');
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    sendSMS() {

      let reg = /^1[0-9]{10}$/
      if (this.loginForm.username == '' || this.loginForm.username.length <= 10 || !reg.test(this.loginForm.username)) {
          this.$message.error('请输入正确的手机号');
          return ;
      }

      this.$store.dispatch('sendSMS', {
        mobile: this.loginForm.username
      })
        .then(res => {
          console.info(res);
        }).catch((ex) => {
        console.info(ex);
      });
      this.triggerSMSCode(true);
    },
    triggerSMSCode(clicked) {
      let smscount = sessionStorage.getItem("smscount");
      console.info('smscount:', smscount);

      if (smscount === null || smscount === '发送验证码') {
        if (clicked) {
          smscount = 10;
        }
      }
      console.info('smscount:', smscount);
      const TIME_COUNT = smscount;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            this.count = "发送验证码";
            clearInterval(this.timer);
            this.timer = null;
          }
          sessionStorage.setItem("smscount", this.count);
        }, 1000)
      }
    }
  }
}
</script>

<style lang="scss">
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-size: cover;

  .form-box {
    width: 320px;
    padding: 15px 30px 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 15px 30px 0 rgba(0, 0, 1, .1);

    .form-title {
      margin: 0 auto 35px;
      text-align: center;
      color: #707070;
      font-size: 18px;
      letter-spacing: 2px;
    }
  }
}
</style>
